iT邦幫忙

2024 iThome 鐵人賽

DAY 6
0

Write an algorithm to determine if a number n is happy.
A happy number is a number defined by the following process:
• Starting with any positive integer, replace the number by the sum of the squares of its digits.
• Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
• Those numbers for which this process ends in 1 are happy.
Return true if n is a happy number, and false if not.

寫一個算法来判斷數字 n 是否為Happy Number。 Happy Number的定義如下:
• 從任何正整數开始,將該數字替换成其每位數字平方和的結果。
• 重複這一過程,直到數字等於 1(此时它會保持不變),或者它陷入一個不包含 1的循環中。
• 那些經過這個過程最終得到 1的數字稱為Happy Number。 如果 n 是Happy Number,則回傳 true;否則回傳 false。
https://ithelp.ithome.com.tw/upload/images/20240818/20168667peEBEhwZ5A.png


先找出規則
如果是Happy Number,那麼最後平方總和會進入 整數1 的循環,所以使用快慢指針去執行平方總和的計算,若快慢指針的數字相等則為Happy Number

來看圖解
https://ithelp.ithome.com.tw/upload/images/20240818/20168667XwTiPSNyIS.png

https://ithelp.ithome.com.tw/upload/images/20240818/20168667JfSlbbTabH.png

解題流程

  • 步驟 1. 先把計算整數的過程寫成一個function(每位數字的平方總和)

  • 步驟 2. 設定快慢指針,快指針(兔子)會比慢指針(烏龜)多執行一次每位數字平方總和

  • 步驟 3. 使用while迴圈,只要快慢指針其中一個不等於1,表示還沒進入循環
    → 每一次迭代快指針執行兩次平方數總和、慢指針執行一次平方數總和

    • 步驟 3-1-2. 若快指針 或 慢指針 其中一個值等於1,表示進入循環,回傳true
    • 步驟 3-1-3. 若快慢指針兩者相等,卻不等於1,表示整數n並非Happy Number,回傳false

解題程式碼

var countNums = function (num) {
  return num.toString().split('').reduce((accumulator, curr) => {    
      return accumulator + (Number(curr) * Number(curr))  
    }, 0)
}
var isHappy = function(n) {
  let rabbit = n
  let turtle = n
  while (rabbit != 1 || turtle !== 1){
    rabbit = countNums(countNums(rabbit))
    turtle = countNums(turtle)
    if (rabbit === 1 || turtle === 1) return true
    if (rabbit === turtle ) return false
  }
  return true
};

上一篇
[Day5]Fast and Slow Pointer & Floyd Cycle Detection Algorithm
下一篇
[Day7] Linked List Cycle II
系列文
刷題筆記20
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言